import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import DataView from "../views/DataView.vue"
import UserView from "../views/User.vue"
const routes = [
  {
    path: '/',
    name: 'home',
    icon: "&#xe61c;",
    text: "首页",
    nav: true,
    component: HomeView
  },
  {
    path: "/data",
    name: "data",
    icon: "&#xe61a;",
    text: "数据",
    nav: true,
    component: DataView
  },
  // {
  //   path:"/message",
  //   name:'message',
  //   icon: "&#xe61a;",
  //   text:"聊天",
  //   nav:true,
  //   component: () => import(/* webpackChunkName: "message" */ "@/views/MessageView.vue"),
  // },
  {
    path: "/user",
    name: "user",
    icon: "&#xe607;",
    text: "个人",
    nav: true,
    component: UserView,
    meta: {
      requiresAuth: false //需要登录
    }
  },
  // 课程列表
  {
    path: "/class",
    name: "class",
    component: () => import(/* webpackChunkName: "setView" */ "@/views/ClassListView.vue"),
    meta: {
      requiresAuth: true //需要登录
    }
  },
  // 添加课程
  {
    path: "/addclass",
    name: "addClass",
    component: () => import(/* webpackChunkName: "AddClassView" */ "@/views/AddClassView.vue"),
    meta: {
      requiresAuth: true //需要登录
    }
  },
  // 地点列表
  {
    path: "/librarylist",
    name: "librarylist",
    component: () => import(/* webpackChunkName: "setView" */ "@/views/libraryListView.vue"),
    meta: {
      requiresAuth: true //需要登录
    }
  },
  // 添加地点
  {
    path: "/addlabrary",
    name: "addlabrary",
    component: () => import(/* webpackChunkName: "addlabrary" */ "@/views/addlabrary.vue"),
    meta: {
      requiresAuth: true //需要登录
    }
  },
  {
    path: "/usersetting",
    name: "usersetting",
    component: () => import(/* webpackChunkName: "addlabrary" */ "@/views/userSetting.vue"),
    meta: {
      requiresAuth: true 
    }
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/LoginVuew.vue")
  },
  {
    path: "/register",
    name: "register",
    component: () => import("@/views/registerView.vue")
  }

]

const router = createRouter({
  mode: "hash",
  // history: createWebHistory(process.env.BASE_URL),//开发用它
  history: createWebHashHistory("/#"), //打包成app的时候用它。
  routes
})

const getToken = () => {
  var token = localStorage.getItem("token");
  if (token) {
    return true;
  } else {
    return false;
  }
}


// 路由守卫 
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 判断当前是否有登录的权限
    if (!getToken()) {
      next({
        path: '/login',
        query: { redirect: to.name }
      })
      // router.push("/login")
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})


export {
  router,
  routes
}
// export default router
